﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class SendSingleSMS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadLogin();
            loadGroup();
        }
    }


    private void loadLogin()
    {
        if (hfLoginID.Value == "")
        {
            hfLoginID.Value = getLogin().ToString();
        }
    }

    private string getLoginID()
    {
        return hfLoginID.Value.Substring(6, hfLoginID.Value.Length - 6).Substring(0, hfLoginID.Value.Length - 12);


    }
    private string getLogin()
    {
        string loginID = "";
        try
        {
            if (Session["OnlineSMS_LoginID"] != null)
            {
                loginID = Session["OnlineSMS_LoginID"].ToString();
            }
            else if (hfLoginID.Value != "")
            {
                loginID = hfLoginID.Value;
            }
            else
            {
                Session["PreviousPage"] = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect("Default.aspx");
            }

        }
        catch (Exception ex)
        { }

        return loginID;
    }

    private void loadGroup()
    {
        string sql = @"
SELECT  [GroupID]
      ,[GroupName]
      ,[dbo].[GetContactCountyLoginID](GroupID) as NoOfContacts
  FROM [Group] where StatusID=1 and LoginID=" + getLoginID() + @"
order by GroupName
";

        DataSet ds = DatabaseManager.ExecSQL(sql);

        chklGroup.Items.Clear();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            chklGroup.Items.Add(new ListItem(dr["GroupName"].ToString() + "(" + decimal.Parse(dr["NoOfContacts"].ToString()).ToString() + ")", dr["GroupID"].ToString()));
        }

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (txtMasking.Text.Trim() == "")
            return;

       

        if (txtSMS.Text.Trim() == "")
            return;

        if(sendToGropIDs()=="")
            return;

        if (!balanceChecking())
        {
            lblReport.Text = "You balance is not sufficient to send SMS";
            return;
        }
        
        int totalSend = 0;
        int totalNotSend = 0;
        int noOfSMS = SendSMS.countSMS(txtSMS.Text.Trim());
        string ids = "";
        try
        {
            string sql = @"

update Login set RemainingSMS-=" + (noOfSMS * totalContactTosend()).ToString() + " where LoginID=" + getLoginID() + @"
                    
INSERT INTO [OnlineSMS].[dbo].[SMS_Job]
           ([SMS]
           ,[LoginID]
           ,[StatusID]
           ,[JobSubmissionDate]
           ,[JobStartedDate]
           ,[LastUpdateDate]
           ,[Size]
            ,[TotalContactTosent]
           ,[LetterCount]
           ,[Masking]
           ,[SendToGroupIDs]
           ,[SendToCount]
           ,[NotSendToCount]
           ,[NotSendTo])
     VALUES
           ('" + txtSMS.Text.Replace("'","''")+@"'--<SMS, nvarchar(max),>
           ,"+getLoginID()+ @"--<LoginID, bigint,>
           ,0--<StatusID, int,>
           ,GETDATE()--<JobSubmissionDate, datetime,>
           ,GETDATE()--<JobStartedDate, datetime,>
           ,GETDATE()--<LastUpdateDate, datetime,>
           ," + noOfSMS.ToString() + @"--<Size, int,>
           ," +totalContactTosend() + @"--<TotalContactTosent, bigint,>
            ," + txtSMS.Text.Trim().Length.ToString() + @"--<LetterCount, int,>
            ,'"+txtMasking.Text+@"'--<Masking, nvarchar(11),>
           ,'"+sendToGropIDs()+@"'--<SendToGroupIDs, nvarchar(max),>
           ,0--<SendToCount, int,>
           ,0--<NotSendToCount, int,>
           ,''--<NotSendTo, nvarchar(max),>
           );
";
            DatabaseManager.ExecSQL(sql);
        }
        catch (Exception ex)
        {
            lblReport.Text = "Error Occured !!! <br/>";
        }
        lblReport.Text = "Your Bulk SMS sending job has stated. You can see the status from Report page.";
            
    }

    private string sendToGropIDs()
    {
        string GroupIDs = "";
        foreach (ListItem item in chklGroup.Items)
        {
            if (item.Selected)
            {
                GroupIDs += (GroupIDs==""?"":",")+item.Value;
            }
        }
        return GroupIDs;
    }

    private bool balanceChecking()
    {

        if (SendSMS.remainingSMS(getLoginID()) >= totalContactTosend()) return true;
            else 
        return false;
    }
    private int totalContactTosend()
    {
        int smsNeedTosend = 0;
        foreach (ListItem item in chklGroup.Items)
        {
            if (item.Selected)
            {
                smsNeedTosend += int.Parse(item.Text.Split('(')[1].Split(')')[0].Trim().Replace(",", ""));
            }
        }
        return smsNeedTosend;
    }
}